package com.gongpingjialoan.activity.car;


import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ClipDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.category.ChooseLikeCarActivity;
import com.gongpingjialoan.activity.main.LoginActivity;
import com.gongpingjialoan.activity.main.MainActivity;
import com.gongpingjialoan.activity.main.ValueReportActivity;
import com.gongpingjialoan.activity.tool.LicenceActivity;
import com.gongpingjialoan.activity.tool.LicenceResultActivity;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.AssessmentData;
import com.gongpingjialoan.bean.car.BaseBean;
import com.gongpingjialoan.bean.car.MainTainData;
import com.gongpingjialoan.bean.car.MyCarBean;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.receiver.ModifyMileBoardCast;
import com.gongpingjialoan.utility.DhUtil;
import com.gongpingjialoan.widget.ModifyMileDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;

import org.json.JSONObject;

import java.lang.reflect.Type;

/**
 */
public class MyLikeCarFragment extends Fragment implements View.OnClickListener, PullToRefreshBase.OnRefreshListener<ScrollView> {

    private View view, lineView;

    private static final int RESULT_LOGIN = 0x917;

    private PullToRefreshScrollView pullToRefreshScrollView;

    private View loadingView, no_likeView, have_likeView;

    private Button carButton;

    private NetDataJson detailNetDataJson;

    private NetDataJson unbindNetDataJson;

    private NetDataJson maintainNetDataJson;

    private NetDataJson modifyMileNetDataJson;

    private static final int VIO_CAR = 0X112;

    private static final int REQUEST_CAR = 0X111;

    private static final int BAOYANG_LOGIN = 0X113;

    private TextView addweizhangTextView, no_maintainTextView, maintain_priceTextView, gongliTextView;

    private MyCarBean myCarBean;

    private BaseBean<MainTainData> mainTainData;

    private ImageView jiagao_imageView , right_goImageView;

//    private ForegroundColorSpan white;

    private boolean isShow = true;

    private LinearLayout mainprogressLinearLayout , no_need_imeLinearLayout, priceLinearLayout, maintain_view, maintain_mainLinearLayout;


    private TextView needImeTextView, recentTextView, jiebangTextView;

    private ForegroundColorSpan priceForegroundColorSpan;

    private int max_miles;

    private TextView priceTextView, changePriceTextView, wanyuaTextView, car_TitleTextView, car_TimeTextView, car_Time_txt, car_MileTextView, car_Mile_txt;

    private Button modify_mile_view;

    private RelativeLayout qushiRelativeLayout;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_my_like_car, container, false);
        initView();
        initData();
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (detailNetDataJson != null) {
            detailNetDataJson.cancelTask();
            detailNetDataJson = null;
        }
        if (maintainNetDataJson != null) {
            maintainNetDataJson.cancelTask();
            maintainNetDataJson = null;
        }
        if (modifyMileNetDataJson != null) {
            modifyMileNetDataJson.cancelTask();
            modifyMileNetDataJson = null;
        }
        if (unbindNetDataJson != null) {
            unbindNetDataJson.cancelTask();
            unbindNetDataJson = null;
        }

    }

    private void initView() {
        pullToRefreshScrollView = (PullToRefreshScrollView) view.findViewById(R.id.scroll_view);
        pullToRefreshScrollView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        pullToRefreshScrollView.setScrollingWhileRefreshingEnabled(false);
        pullToRefreshScrollView.setOnRefreshListener(this);
        qushiRelativeLayout = (RelativeLayout) view.findViewById(R.id.qushi_view);
        jiagao_imageView = (ImageView) view.findViewById(R.id.jingao);
        no_need_imeLinearLayout = (LinearLayout) view.findViewById(R.id.no_need_ime);
        lineView = (View) view.findViewById(R.id.all_progress_id);
        needImeTextView = (TextView) view.findViewById(R.id.need_ime_text);
        jiebangTextView = (TextView) view.findViewById(R.id.jiebang_id);
        recentTextView = (TextView) view.findViewById(R.id.recent_id);
        gongliTextView = (TextView) view.findViewById(R.id.text_gongli);
        maintain_priceTextView = (TextView) view.findViewById(R.id.main_price);
        no_maintainTextView = (TextView) view.findViewById(R.id.no_maintain);
        maintain_mainLinearLayout = (LinearLayout) view.findViewById(R.id.baoyang_main);
        maintain_view = (LinearLayout) view.findViewById(R.id.maintain_view);
        mainprogressLinearLayout = (LinearLayout) view.findViewById(R.id.main_progress);
        right_goImageView = (ImageView)view.findViewById(R.id.right_go_view);
        modify_mile_view = (Button) view.findViewById(R.id.modify_mile_view);
        car_TitleTextView = (TextView) view.findViewById(R.id.car_title);
        car_TimeTextView = (TextView) view.findViewById(R.id.car_time);
        car_Time_txt = (TextView) view.findViewById(R.id.car_time_text);
        car_MileTextView = (TextView) view.findViewById(R.id.car_mile);
        car_Mile_txt = (TextView) view.findViewById(R.id.car_mile_text);
        wanyuaTextView = (TextView) view.findViewById(R.id.wanyuan_id);
        changePriceTextView = (TextView) view.findViewById(R.id.change_price);
        priceTextView = (TextView) view.findViewById(R.id.price);
        priceLinearLayout = (LinearLayout) view.findViewById(R.id.price_change_bg);
        addweizhangTextView = (TextView) view.findViewById(R.id.weizhang_id);
        loadingView = view.findViewById(R.id.main_loading);
        no_likeView = view.findViewById(R.id.no_like_main);
        have_likeView = view.findViewById(R.id.have_like_car);
        carButton = (Button) view.findViewById(R.id.car_btn);
        carButton.setOnClickListener(this);
        modify_mile_view.setOnClickListener(this);
        addweizhangTextView.setOnClickListener(this);
        priceLinearLayout.setOnClickListener(this);
        jiebangTextView.setOnClickListener(this);
        loadingView.setVisibility(View.VISIBLE);
        no_likeView.setVisibility(View.GONE);
        have_likeView.setVisibility(View.GONE);
        clipDrawable = (ClipDrawable) qushiRelativeLayout.getBackground();

    }


    private void initData() {
        clipDrawable.setLevel(0);
        max_miles = -1;

        ViewGroup.LayoutParams lv =  lineView.getLayoutParams();
        lv.width = 0 ;
        lineView.setLayoutParams(lv);

        right_goImageView.setVisibility(View.GONE);
        recentTextView.setVisibility(View.GONE);
        no_maintainTextView.setVisibility(View.GONE);
        no_need_imeLinearLayout.setVisibility(View.VISIBLE);
        maintain_priceTextView.setVisibility(View.GONE);
        maintain_view.setVisibility(View.INVISIBLE);
        maintain_view.setTranslationX(0);
        detailNetDataJson = new NetDataJson(new NetDataJson.OnStringListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
                sendMessage("fail");
                pullToRefreshScrollView.onRefreshComplete();
                loadingView.setVisibility(View.GONE);
                Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDataJsonUpdate(String json) {
                try {
                    Gson gson = new Gson();
                    Type type = new TypeToken<BaseBean<MyCarBean>>() {
                    }.getType();
                    BaseBean<MyCarBean> myCarBeanBaseBean = gson.fromJson(json, type);
                    myCarBean = myCarBeanBaseBean.getData();
                    if ("success".equals(myCarBeanBaseBean.getStatus())) {
                        if ("没有符合条件的结果".equals(myCarBeanBaseBean.getMsg())) {
                            sendMessage("fail");
                            loadingView.setVisibility(View.GONE);
                            no_likeView.setVisibility(View.VISIBLE);
                            have_likeView.setVisibility(View.GONE);
                            pullToRefreshScrollView.onRefreshComplete();
                        } else {
                            have_likeView.setVisibility(View.VISIBLE);
                            no_likeView.setVisibility(View.GONE);
                            getMaintainData();
                            initWeizhangView();
                            initPriceChangeView();
                        }
                    } else {
                        sendMessage("fail");
                        pullToRefreshScrollView.onRefreshComplete();
                        loadingView.setVisibility(View.GONE);
                        Toast.makeText(getActivity(), "数据异常，请检查网络连接或稍后重试。", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    sendMessage("fail");
                    loadingView.setVisibility(View.GONE);
                    pullToRefreshScrollView.onRefreshComplete();
                    Toast.makeText(getActivity(), "数据异常，请检查网络连接或稍后重试。", Toast.LENGTH_SHORT).show();
                }
            }
        }, 1);
        detailNetDataJson.setUrl(API.like_car_detail);
        detailNetDataJson.request("get");
    }


    private void sendMessage(String msg) {
        Intent intent = new Intent(ModifyMileBoardCast.MODIFY_MILE_ACTION);
        intent.putExtra("msg", msg);
        if ("success".equals(msg)) {
            intent.putExtra("carbean", myCarBean);
            intent.putExtra("maintain", mainTainData.getData());
        }
        getActivity().sendBroadcast(intent);
    }


    /**
     * 获取保养数据
     */
    private void getMaintainData() {
        if (maintainNetDataJson == null) {
            maintainNetDataJson = new NetDataJson(new NetDataJson.OnStringListener() {
                @Override
                public void onDataJsonError(String errorMessage) {
                    sendMessage("fail");
                    max_miles = -1;
                    maintain_mainLinearLayout.setOnClickListener(null);
                    pullToRefreshScrollView.onRefreshComplete();
                    loadingView.setVisibility(View.GONE);
                    right_goImageView.setVisibility(View.GONE);
                    no_maintainTextView.setVisibility(View.VISIBLE);
                    maintain_priceTextView.setVisibility(View.GONE);
                    needImeTextView.setVisibility(View.GONE);
                    recentTextView.setVisibility(View.GONE);
                    mainprogressLinearLayout.setVisibility(View.GONE);
                    if (isShow) {
                        Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT).show();
                    }
                    isShow = true;
                }

                @Override
                public void onDataJsonUpdate(String json) {
                    try {
                        Gson gson = new Gson();
                        Type type = new TypeToken<BaseBean<MainTainData>>() {
                        }.getType();
                        mainTainData = gson.fromJson(json, type);

                        if ("false".equals(mainTainData.getStatus())) {
                            max_miles = -1;
                            maintain_mainLinearLayout.setOnClickListener(null);
                            pullToRefreshScrollView.onRefreshComplete();
                            right_goImageView.setVisibility(View.GONE);
                            loadingView.setVisibility(View.GONE);
                            no_maintainTextView.setVisibility(View.VISIBLE);
                            maintain_priceTextView.setVisibility(View.GONE);
                            needImeTextView.setVisibility(View.GONE);
                            recentTextView.setVisibility(View.GONE);
                            mainprogressLinearLayout.setVisibility(View.GONE);
                            sendMessage("fail");
                            if (isShow) {
                                Toast.makeText(getActivity(), mainTainData.getMsg(), Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            sendMessage("success");
                            mainprogressLinearLayout.setVisibility(View.VISIBLE);
                            right_goImageView.setVisibility(View.VISIBLE);
                            max_miles = mainTainData.getData().getNext().getMax_kilometers();
                            if (mainTainData.getData().getMaintain().size() > 1) {
                                priceForegroundColorSpan = new ForegroundColorSpan(getActivity().getResources().getColor(R.color.text_orange_dark));
                                String price = mainTainData.getData().getMaintain().get(0).getPrice() + "";
                                if ("0".equals(price)) {
                                    maintain_priceTextView.setVisibility(View.GONE);
                                } else {
                                    int size = price.length();
                                    SpannableStringBuilder builder = new SpannableStringBuilder("预计花 " + price + " 元");
                                    builder.setSpan(priceForegroundColorSpan, 4, 4 + size, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    maintain_priceTextView.setText(builder);
                                    maintain_priceTextView.setVisibility(View.VISIBLE);
                                }
                            }

                            if (mainTainData.getData().getNext().isNeed_maintain_immediately()) {
                                no_need_imeLinearLayout.setVisibility(View.GONE);
                                needImeTextView.setVisibility(View.INVISIBLE);
                                recentTextView.setVisibility(View.VISIBLE);
                                lineView.setBackgroundResource(R.color.maintain_progress_color);
                                location(1);
                            } else {
                                recentTextView.setVisibility(View.GONE);
                                needImeTextView.setVisibility(View.VISIBLE);
                                no_need_imeLinearLayout.setVisibility(View.VISIBLE);
                                lineView.setBackgroundResource(R.color.maintain_progress);
                                double r_miles = mainTainData.getData().getNext().getKilometers();
                                double all_miles = mainTainData.getData().getNext().getMaintain_interval_kilometers();
                                gongliTextView.setText((int) r_miles + "");
                                double progess = (all_miles - r_miles) / all_miles;
                                location(progess);
                            }
                            no_maintainTextView.setVisibility(View.GONE);
                            loadingView.setVisibility(View.GONE);
                            pullToRefreshScrollView.onRefreshComplete();
                            maintain_mainLinearLayout.setOnClickListener(MyLikeCarFragment.this);
                        }

                    } catch (Exception e) {
                        sendMessage("fail");
                        max_miles = -1;
                        mainprogressLinearLayout.setVisibility(View.GONE);
                        maintain_mainLinearLayout.setOnClickListener(null);
                        pullToRefreshScrollView.onRefreshComplete();
                        loadingView.setVisibility(View.GONE);
                        no_maintainTextView.setVisibility(View.VISIBLE);
                        maintain_priceTextView.setVisibility(View.GONE);
                        needImeTextView.setVisibility(View.GONE);
                        recentTextView.setVisibility(View.GONE);
                        lineView.setVisibility(View.GONE);
                        right_goImageView.setVisibility(View.GONE);
                        if (isShow) {
                            Toast.makeText(getActivity(), "保养数据异常，请稍后再试！", Toast.LENGTH_SHORT).show();
                        }
                    }
                    isShow = true;
                }
            }, 1);

        }
        maintainNetDataJson.setUrl(API.maintain_details);
        maintainNetDataJson.setUseOtherDomain(true);
        maintainNetDataJson.addParam("mycar_id", myCarBean.getId());
        maintainNetDataJson.request("get");

    }

    private ClipDrawable clipDrawable;

    private ValueAnimator valueAnimator;

    private ValueAnimator progressValueAnimator;

    private void location(double progress) {

        final ViewGroup.LayoutParams lv =  lineView.getLayoutParams();
        int width = DhUtil.dip2px(getActivity(), 150);
        int minmiles = width / 2;
        int spalshWidth = getActivity().getResources().getDisplayMetrics().widthPixels;
        int maxmiles = spalshWidth - width;
        float lineWidth;



        //据算margin的距离   两个圆之间的总距离*progress - 减去view_width/2  + 一个圆球宽度/2
        final float marginLeft;
        if (progress == 0) {
            //1*5
            marginLeft = 0;
            lineWidth = minmiles;
        } else {
            //2*5
            marginLeft = (float) (maxmiles * progress);
            lineWidth = marginLeft + minmiles;
        }

//        ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) maintain_view.getLayoutParams();
//        marginLayoutParams.leftMargin = marginLeft;
//        maintain_view.setLayoutParams(marginLayoutParams);
        AnimatorSet animatorSet = new AnimatorSet();
        valueAnimator = ValueAnimator.ofInt(0, 10000);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int value = (int) animation.getAnimatedValue();
                clipDrawable.setLevel(value);
            }
        });

        progressValueAnimator = ValueAnimator.ofFloat(0f, lineWidth);
        progressValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (Float) animation.getAnimatedValue();
                lv.width = (int) value;
                lineView.setLayoutParams(lv);
            }
        });
        progressValueAnimator.setInterpolator(new AccelerateDecelerateInterpolator());

        animatorSet.setDuration(800).setInterpolator(new AccelerateDecelerateInterpolator());
        animatorSet.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                maintain_view.setVisibility(View.VISIBLE);
                maintain_view.animate().translationX(marginLeft).setDuration(400).setInterpolator(new DecelerateInterpolator()).start();
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        animatorSet.play(valueAnimator).with(progressValueAnimator);
        animatorSet.start();


    }


    /**
     * 加载价格变化信息
     */
    private void initPriceChangeView() {
        if (myCarBean.getPrice_diff() == 0) {
            priceLinearLayout.setBackgroundResource(R.drawable.price_no_change);
            priceTextView.setTextColor(getResources().getColor(R.color.price_no_change_color));
            priceTextView.setText(myCarBean.getEval_price());
            wanyuaTextView.setTextColor(getResources().getColor(R.color.price_no_change_color));
            wanyuaTextView.setText("万元");
            changePriceTextView.setText("您的爱车价格平稳");
        } else if (myCarBean.getPrice_diff() < 0) {
            priceLinearLayout.setBackgroundResource(R.drawable.price_up);
            priceTextView.setText(myCarBean.getEval_price());
            priceTextView.setTextColor(getResources().getColor(R.color.price_up_color));
            wanyuaTextView.setText("万元");
            wanyuaTextView.setTextColor(getResources().getColor(R.color.price_up_color));
            changePriceTextView.setText("比上次\n升了" + Math.abs(myCarBean.getPrice_diff()) + "元");
        } else {
            priceLinearLayout.setBackgroundResource(R.drawable.price_down);
            priceTextView.setText(myCarBean.getEval_price());
            priceTextView.setTextColor(getResources().getColor(R.color.price_down_color));
            wanyuaTextView.setText("万元");
            wanyuaTextView.setTextColor(getResources().getColor(R.color.price_down_color));
            changePriceTextView.setText("比上次\n降了" + myCarBean.getPrice_diff() + "元");
        }
        car_TitleTextView.setText(myCarBean.getModel_zh() + myCarBean.getModel_detail_zh());
        car_TimeTextView.setText(myCarBean.getYear() + "年" + myCarBean.getMonth() + "月上牌");

        car_Time_txt.setText("已行驶");
        car_MileTextView.setText(myCarBean.getMile());
        car_Mile_txt.setText("万公里");

//        double proble_miles = Math.abs(Double.parseDouble(myCarBean.getProbable_mile()) - Double.parseDouble(myCarBean.getMile()))*10000;
//        if(proble_miles >= 100){
//            modfiy_main.setVisibility(View.VISIBLE);
//        }else{
//            modfiy_main.setVisibility(View.VISIBLE);
//        }

    }


    /**
     * 加载违章信息
     */
    private void initWeizhangView() {
        if ("".equals(myCarBean.getLicense_num())) {
            jiagao_imageView.setVisibility(View.GONE);
            jiebangTextView.setVisibility(View.GONE);
            addweizhangTextView.setTag(0);
            addweizhangTextView.setText("＋  添加违章查询");
            addweizhangTextView.setTextColor(getActivity().getResources().getColor(R.color.grey_white));
        } else {
            if (myCarBean.getViolate() == 0) {
                jiagao_imageView.setVisibility(View.GONE);
                addweizhangTextView.setTag(1);
                addweizhangTextView.setText("暂无违章记录");
                addweizhangTextView.setTextColor(getActivity().getResources().getColor(R.color.grey_white));
            } else {
                addweizhangTextView.setTag(2);
//                white = new ForegroundColorSpan(getActivity().getResources().getColor(R.color.white));
                addweizhangTextView.setTextColor(getActivity().getResources().getColor(R.color.weizhang_text));
//                int size = (myCarBean.getViolate() + "").length();
                String title = "您有 " + myCarBean.getViolate() + " 条违章信息未查看";
                jiagao_imageView.setVisibility(View.VISIBLE);
//                SpannableStringBuilder builder = new SpannableStringBuilder(title);
//                builder.setSpan(white, 3, 3 + size, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                addweizhangTextView.setText(title);
            }
            jiebangTextView.setVisibility(View.VISIBLE);
        }
    }


    @Override
    public void onClick(View v) {
        if (v == carButton) {
            startActivityForResult(new Intent(getActivity(), ChooseLikeCarActivity.class), REQUEST_CAR);
        } else if (v == addweizhangTextView) {
            int tag = (int) addweizhangTextView.getTag();
            if (tag == 0) {
                if (GPJApplication.getInstance().isLogin()) {
                    Intent intent = new Intent();
                    intent.putExtra("type", 1);
                    intent.putExtra("id", myCarBean.getId());
                    intent.setClass(getActivity(), LicenceActivity.class);
                    startActivityForResult(intent, VIO_CAR);
                } else {
                    // 没有登陆
                    Intent it = new Intent(getActivity(), LoginActivity.class);
                    startActivityForResult(it, RESULT_LOGIN);
                }


            } else if (tag == 2) {
                Intent intent = new Intent();
                intent.putExtra("license_num", myCarBean.getLicense_num());
                intent.putExtra("licence_prefix", myCarBean.getLicence_prefix());
                intent.putExtra("province", myCarBean.getProvince());
                if (!myCarBean.getEngine_number().isEmpty()) {
                    intent.putExtra("engine_number", myCarBean.getEngine_number());
                }
                intent.putExtra("city_pinyin", myCarBean.getCity_pinyin());
                if (!myCarBean.getVin().isEmpty()) {
                    intent.putExtra("body_number", myCarBean.getVin());
                }
                intent.setClass(getActivity(), LicenceResultActivity.class);
                startActivity(intent);
            }
        } else if (v == modify_mile_view) {
            ModifyMileDialog modifyMileDialog = new ModifyMileDialog(getActivity(), max_miles, this, 0);
            modifyMileDialog.show();
        } else if (v == maintain_mainLinearLayout) {
            if (GPJApplication.getInstance().isLogin()) {
                Intent intent = new Intent(getActivity(), MainTainActivity.class);
                intent.putExtra("carbean", myCarBean);
                intent.putExtra("maintain", mainTainData.getData());
                startActivity(intent);
            } else {
                // 没有登陆
                Intent it = new Intent(getActivity(), LoginActivity.class);
                startActivityForResult(it, BAOYANG_LOGIN);
            }


        } else if (v == jiebangTextView) {

            android.support.v7.app.AlertDialog.Builder ab = new android.support.v7.app.AlertDialog.Builder(getActivity());
            ab.setTitle("提示");
            ab.setMessage("是否解除违章信息的绑定");
            ab.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    unbind();
                }
            });
            ab.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
            ab.create().show();

        } else if (v == priceLinearLayout) {
            assessData();
        }
    }


    private void assessData() {
        AssessmentData data = AssessmentData.getInstance();
        data.clear();
        data.setBrandName("");
        data.setBrandSlug(myCarBean.getBrand_slug());
        data.setMile(myCarBean.getMile());
        data.setModelDetailName("");
        data.setModelDetailSlug(myCarBean.getModel_detail_slug());
        data.setModelName("");
        data.setModelSlug(myCarBean.getModel_slug());
        data.setModelThumbnail(myCarBean.getThumbnail());
        data.setMonth(myCarBean.getMonth() + "");
        data.setYear(myCarBean.getYear() + "");
//        data.setType(getType());
        data.setCity(myCarBean.getCity());
        data.setCar_id("");

        Intent it = new Intent(getActivity(), ValueReportActivity.class);
        it.putExtra("isassessment", true);

        String weburl = API.assessCarUrl
                + data.getBrandSlug() + "/" + data.getModelSlug()
                + "/" + data.getModelDetailSlug() + "/"
                + data.getYear() + "-" + data.getMonth() + "/"
                + data.getMile() + "/";


        it.putExtra("url", weburl);
        it.putExtra("title", "估值报告");
        it.putExtra("content", "");
        it.putExtra("isassessment", true);
        it.putExtra("isfromlikecar", true);
        getActivity().startActivity(it);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_CAR || requestCode == VIO_CAR) {
                pullToRefreshScrollView.setRefreshing();
            } else if (requestCode == RESULT_LOGIN || requestCode == BAOYANG_LOGIN) {
                pullToRefreshScrollView.setRefreshing();
                //登录后不直接进入到违章页面和保养页面
//                Intent intent = new Intent();
//                intent.putExtra("type", 1);
//                intent.putExtra("id", myCarBean.getId());
//                intent.setClass(getActivity(), LicenceActivity.class);
//                startActivityForResult(intent, VIO_CAR);

            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
        loadingView.setVisibility(View.GONE);
        initData();
    }


    //修改里程数
    public void modifymiles(String miles) {
        loadingView.setVisibility(View.VISIBLE);
        if (modifyMileNetDataJson == null) {
            modifyMileNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                @Override
                public void onDataJsonError(String errorMessage) {
                    loadingView.setVisibility(View.GONE);
                    Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onDataJsonUpdate(JSONObject json) {
                    loadingView.setVisibility(View.GONE);
                    if(MainActivity.main!=null){
                        MainActivity.main.mUserHomeFragment.refresh();
                    }
                    Toast.makeText(getActivity(), "修改成功", Toast.LENGTH_SHORT).show();
                    refresh(true);
                }
            });
        }
        modifyMileNetDataJson.addParam("mileage", miles);
        modifyMileNetDataJson.addParam("my_car_id", myCarBean.getId());
        modifyMileNetDataJson.setUrl(API.modify_miles);
        modifyMileNetDataJson.request("post");
    }


    public void refresh(boolean isShow) {
        this.isShow = isShow;
        if (pullToRefreshScrollView != null) {
            pullToRefreshScrollView.setRefreshing();
        }

    }


    private void unbind() {
        loadingView.setVisibility(View.VISIBLE);
        if (unbindNetDataJson == null) {
            unbindNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                @Override
                public void onDataJsonError(String errorMessage) {
                    loadingView.setVisibility(View.GONE);
                    Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onDataJsonUpdate(JSONObject json) {
                    loadingView.setVisibility(View.GONE);
                    Toast.makeText(getActivity(), "解除绑定成功", Toast.LENGTH_SHORT).show();
                    refresh(true);
                }
            });
        }

        unbindNetDataJson.setUrl(API.unbind);
        unbindNetDataJson.addParam("my_car_id", myCarBean.getId());
        unbindNetDataJson.request("post");
    }

}
